namespace StudentManagerService;

using System;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using StudentMapper;


public class BackendServer
{

    WebApplication _app;

    private BackendServer(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        builder.Services.AddDbContext<StudentMapper>(opt => opt.UseInMemoryDatabase("StudentList"));
        builder.Services.AddDatabaseDeveloperPageExceptionFilter();
        this._app = builder.Build();
    }

    private BackendServer InitRoute()
    {
        //_app.mapget("/student/1", () => "{\"name\": \"nick\", \"id\": \"1\"}");
        //_app.MapGet("/student", () =>
        //{
        //    var stu = new StudentEntity
        //    {
        //        Name = "afterloe",
        //        Source = 18,
        //        CreateTime = DateTime.Now
        //    };

        //    return JsonConvert.SerializeObject(stu, Formatting.Indented);
        //});

        // 创建学生
        _app.MapPut("/student", async (StudentEntity entity, StudentMapper mapper) =>
        {
            if (entity.Id is null) return Results.BadRequest("id is null");
            entity.CreateTime = DateTime.Now;
            mapper.Students.Add(entity);
            await mapper.SaveChangesAsync();

            return Results.Ok("create success.");
        });

        // 查询学生列表
        _app.MapGet("/student/list", async (StudentMapper mapper) => await mapper.Students.ToListAsync());

        // 精确查询学生
        _app.MapGet("/student/{id}", async (int id, StudentMapper mapper) =>
            await mapper.Students.FindAsync(id)
                is StudentEntity student ? Results.Ok(student) : Results.NotFound($"{id} 对应的学生没有找到")
        );

        // 修改学生成绩
        _app.MapPost("/student/{id}", async (int id, StudentEntity input, StudentMapper mapper) => {
            var stu = await mapper.Students.FindAsync(id);
            if (stu is null) return Results.NotFound($"{id} 对应的学生没有找到");
            stu.Source = input.Source;
            await mapper.SaveChangesAsync();
            return Results.Ok("success!");
        });

        // 删除学生
        _app.MapDelete("/student/{id}", async (int id, StudentMapper mapper) => { 
       
            if (await mapper.Students.FindAsync(id) is StudentEntity entity)
            {
                mapper.Students.Remove(entity);
                await mapper.SaveChangesAsync();
                return Results.Ok("success!");
            }

            return Results.NotFound($"{id} 对应的学生没有找到");
        });

        return this;
    }

    private BackendServer Run()
    {
        this._app.Run();
        return this;
    }


    public static void Main(string[] args)
    {
        new BackendServer(args).InitRoute().Run();
    }
}
